import * as CONSTANT from '../constant';

//01 state : 抽离数据
const defaultState = {tasks:[],task:''}

//02 reducer : 抽离行为
const reducer  = (state=defaultState,action)=>{
   switch (action.type) {
       case CONSTANT.TASK_INIT:
        //  console.log('action',action);
         const tasks = action.payload
         return {...state,tasks}
       case CONSTANT.TASK_SYNC:
           let task  = action.payload
           return {...state,task}
       case CONSTANT.TASK_ADD:
            let taskNew = { task: state.task, date: new Date().toLocaleDateString() }
             // state.task需要深度拷贝
            // 1） 原来数组拷贝 后追加任务
            let newTasks = [...state.tasks]
            newTasks.unshift(taskNew)
            // 2) 后追加任务 后原来数组拷贝 
            // state.tasks.unshift(taskNew)
            // let newTasks = [...state.tasks]
            state.task = ''
            return {...state,tasks:newTasks} 
            // 3)JSON.parse 和 JSON.stringify 配合使用
            // let newState = JSON.parse(JSON.stringify(state))
            // newState.tasks.unshift(taskNew)
            // newState.task = ''
            // return newState
       case CONSTANT.TASK_DELETE:
            const index = action.payload
            state.tasks = [...state.tasks]
            state.tasks.splice(index, 1)
            return {...state}
       default:
           return state
   }
 
}

export default reducer